
import React,{useState } from 'react';
import ReactDOM from 'react-dom';
import './Portals.css'

function Parent() {
    const [isModalOpen,setIsModalOpen] = useState(false);
    return (
        <div style={{ overflow: 'hidden' }}>
            <button onClick={()=>setIsModalOpen(true)}>打开弹框</button>
            {
                isModalOpen && 
                <Modal title="示例弹窗" isOpen={isModalOpen} onClose={() => setIsModalOpen(false)}>
                    <p>这是一个使用React Portals实现的模态框。</p>
                    <p>它支持点击外部关闭、ESC键关闭等功能。</p>
                </Modal>
            }
        </div>
    )
}

const Modal = ({ isOpen,onClose,children}) => {
    if(!isOpen) return null;
    const portalRoot = document.getElementById('protals-root')
    
    return ReactDOM.createPortal(
        <div className="modal-overlay" onClick={ onClose }>
            <div className="modal-content" onClick={(e)=>e.stopPropagation()}>
                { children }
                <button onClick={onClose}>关闭</button>
            </div>
        </div>,
        portalRoot,
    )
}

// Portals提供了一种将子节点渲染到存在于父组件以外的DOM节点的优秀的方案。
export default function Portals() {
    return (
        <div>
            <h1>Portals</h1>
            <div id="protals-root"></div>
            <Parent />
        </div>
    )
}